"""
初始化商品数据：创建50条带图片与库存的商品
运行方式：
    python tools/seed_goods.py
"""
from sqlalchemy.orm import Session
from random import randint, choice, uniform
from decimal import Decimal

from database.base import SessionLocal, engine
from models.goods_models import Goods
from database.base import Base
from sqlalchemy import text

IMAGE_POOL = [
    # 可替换为你自己的静态图地址
    "https://images.unsplash.com/photo-1526170375885-4d8ecf77b99f",
    "https://images.unsplash.com/photo-1512496015851-a90fb38ba796",
    "https://images.unsplash.com/photo-1517686469429-8bdb88b9f907",
    "https://images.unsplash.com/photo-1513708925888-6baf1708d2d4",
    "https://images.unsplash.com/photo-1503602642458-232111445657",
    "https://images.unsplash.com/photo-1517336714731-489689fd1ca8",
    "https://images.unsplash.com/photo-1505740420928-5e560c06d30e",
    "https://images.unsplash.com/photo-1526178618718-507ef42542b3",
]

CATEGORIES = ["美妆", "服饰", "家居", "数码", "运动", "母婴", "零食", "饰品"]


def ensure_tables():
    # 确保表存在（只会创建缺失表）
    Base.metadata.create_all(bind=engine)
    # 确认goods表包含stock列（MySQL，兼容各版本）
    with engine.connect() as conn:
        # 查询是否存在stock列
        check_sql = text("""
            SELECT COUNT(*) AS cnt
            FROM information_schema.COLUMNS
            WHERE TABLE_SCHEMA = :db AND TABLE_NAME = 'goods' AND COLUMN_NAME = 'stock'
        """)
        result = conn.execute(check_sql, {"db": engine.url.database}).scalar()
        if not result:
            # 不存在则添加
            conn.execute(text("ALTER TABLE goods ADD COLUMN stock INT DEFAULT 0 COMMENT '库存数量'"))
            conn.commit()


def generate_goods(i: int) -> Goods:
    name = f"优选好物 {i+1} 号"
    description = f"这是第 {i+1} 件优选好物，质感出众，性价比高，日常必备。"
    price = Decimal(str(round(uniform(19.9, 999.0), 2)))
    image_url = choice(IMAGE_POOL) + "?auto=format&fit=crop&w=800&q=60"
    category = choice(CATEGORIES)
    stock = randint(5, 300)
    return Goods(
        name=name,
        description=description,
        price=price,
        image_url=image_url,
        category=category,
        stock=stock,
        status=1,
    )


def seed(count: int = 50):
    ensure_tables()
    db: Session = SessionLocal()
    try:
        existing = db.query(Goods).count()
        if existing >= count:
            print(f"已存在 {existing} 条商品，跳过初始化")
            return

        items = [generate_goods(i) for i in range(count)]
        db.add_all(items)
        db.commit()
        print(f"已成功插入 {count} 条商品数据")
    except Exception as e:
        db.rollback()
        print(f"插入失败: {e}")
        raise
    finally:
        db.close()


if __name__ == "__main__":
    seed(50)


